﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YearsGoneBy.ViewModels.Photos;
using YearsGoneBy.Models;
using System.Linq;
using System.IO;

namespace YearsGoneBy.Controllers
{
    public class PhotosController : Controller
    {
        // GET: RegisteredUser
        protected YearsGoneByConnection _data = new YearsGoneByConnection();

        public ActionResult PhotoSubmision()
        {

            var PhotoSubmisionViewModel = new PhotoSubmisionViewModel()
            {
                Active = true,
                SubmitiedBy = User.Identity.Name,
                PhotoLat = 0,
                PhotoLon = 0,
                
            };

            return View(PhotoSubmisionViewModel);
        }

        [HttpPost]
        public ActionResult PhotoSubmision(PhotoSubmisionViewModel PhotoSubmisionViewModel, HttpPostedFileBase  file )
        {
            if (file.ContentLength < Convert.ToInt64(3000000000))
            {


                if (ModelState.IsValid)
                {
                    var Photo = new Photo
                    {
                        Active = PhotoSubmisionViewModel.Active,
                        PhotoDescription = PhotoSubmisionViewModel.PhotoDescription,
                        PhotoLat = PhotoSubmisionViewModel.PhotoLat,
                        PhotoLon = PhotoSubmisionViewModel.PhotoLon,
                        PhotoLocation = PhotoSubmisionViewModel.PhotoLocation,
                        SubmitiedBy = PhotoSubmisionViewModel.SubmitiedBy,
                        Year = PhotoSubmisionViewModel.Year,
                    };

                    if (file.ContentLength > 0)
                    {
                        Photo.Photo1 = SavePhotos(file, PhotoSubmisionViewModel.Year.ToString());
                    }

                    _data.Entry(Photo).State = System.Data.Entity.EntityState.Added;
                    _data.SaveChanges();

                }

                return RedirectToAction("PhotoSubmisionConformation");
            }
            ViewBag.Error = "The file size is to large";
            return View(PhotoSubmisionViewModel);
        }
        
        public string SavePhotos(HttpPostedFileBase file, string year)
        {
            var folder = HttpRuntime.AppDomainAppVirtualPath + ("img/Photos/" + year + "/");
            var serverfolder = Server.MapPath("~/img/Photos/" + year + "/");

            if (!Directory.Exists(serverfolder))
            {
                Directory.CreateDirectory(serverfolder);
            }

            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(serverfolder, fileName);
            file.SaveAs(path);

            return Path.Combine(folder, fileName);
        }

    }
}